﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Migracion.Process;
using System.IO;
using System.Diagnostics;

namespace WinFormImportador
{
    public partial class MigracionAPSAE : Form
    {
        private JurisprudenciaProc JurisprudenciaProc;
        private DoctrinaProc DoctrinaProc;
        private LegislacionProc LegislacionProc;
        private StreamWriter LogFile;

        public MigracionAPSAE()
        {
            InitializeComponent();
        }

        private void MigracionAPSAE_Load(object sender, EventArgs e)
        {
            this.txtOutputJuris.Text = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Documentos");
            this.txtCitaAp.Text = "20000176"; // "70003199";
            this.btnDetenerJuris.Visible = false;
        }

        private void bkWorkerJuris_DoWork(object sender, DoWorkEventArgs e)
        {
            if (JurisprudenciaProc != null)
            {
                JurisprudenciaProc.DoProcess();
            }
            else if (DoctrinaProc != null)
            {
                DoctrinaProc.DoProcess();
            }
            else if (LegislacionProc != null)
            {
                LegislacionProc.DoProcess();
            }
        }

        private void bkWorkerJuris_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {            
            ErrorLog errorLog = e.UserState as ErrorLog;
            if (errorLog != null)
            {
                if (LogFile != null)
                {
                    LogFile.WriteLine(string.Format("Doc: {0},{1} Mensaje: {2}", errorLog.Id, errorLog.Status.ToString(), errorLog.Message));
                }
                else
                {
                    lstLog.Items.Add(errorLog.Message);
                }
            }
            else
            {
                ProgressStatusClass status = e.UserState as ProgressStatusClass;
                if (status != null)
                {
                    if(chkLogAArchivo.Checked)
                    {
                        this.lstLog.Items.Clear();
                    }

                    this.lstLog.Items.Add(string.Format("Procesados: {0} / {1}", status.Actual, status.Total));
                }
            }
        }

        private void bkWorkerJuris_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.btnDetenerJuris.Visible = false;
            this.btnProcesarJurisprudencia.Visible = true;
            this.btnProcesarLegislacion.Visible = true;
            this.btnObras.Visible = true;
            this.btnProcesarDoctrina.Visible = true;

            if (LogFile != null)
            {
                LogFile.Close();
                LogFile = null;
            }
        }

        private void btnProcesarJurisprudencia_Click(object sender, EventArgs e)
        {
            LegislacionProc = null;
            DoctrinaProc = null;
            JurisprudenciaProc = new JurisprudenciaProc();
            JurisprudenciaProc.OnLogStatus += GetLogStatusDelegate();
            JurisprudenciaProc.OnProgressStatus += new Migracion.Process.ProgressStatus(ProgressStatus);

            this.btnDetenerJuris.Visible = true;
            this.btnProcesarJurisprudencia.Visible = false;
            this.btnProcesarDoctrina.Visible = false;
            this.btnObras.Visible = false;
            this.btnProcesarLegislacion.Visible = false;

            if (!Directory.Exists(this.txtOutputJuris.Text))
            {
                Directory.CreateDirectory(this.txtOutputJuris.Text);
            }

            JurisprudenciaProc.SQLText = this.txtSql.Text;
            JurisprudenciaProc.OutputPath = this.txtOutputJuris.Text;
            JurisprudenciaProc.AbeledoId = this.txtCitaAp.Text;
            JurisprudenciaProc.ProcesarTextoCompleto = !this.chkSoloSumario.Checked;

            bkWorkerJuris.RunWorkerAsync();
        }       

        private LogStatus GetLogStatusDelegate()
        {
            if (chkLogAArchivo.Checked)
            {
                string filePath = Path.Combine(this.txtLogPath.Text, string.Format("LogMigApll_{0:yyyyMMdd hhmmss}.txt", DateTime.Now));

                if (!Directory.Exists(this.txtLogPath.Text))
                {
                    Directory.CreateDirectory(this.txtLogPath.Text);
                }

                LogFile = File.CreateText(filePath);     

            }

            return new LogStatus(Proc_OnLogStatus);
        }

        private void ProgressStatus(int procesado, int total)
        {
            ProgressStatusClass prog = new ProgressStatusClass();
            prog.Actual = procesado;
            prog.Total = total;
            bkWorkerJuris.ReportProgress(0, prog);
        }


        private void btnProcesarDoctrina_Click(object sender, EventArgs e)
        {
            LegislacionProc = null;
            DoctrinaProc = new DoctrinaProc();
            JurisprudenciaProc = null;

            DoctrinaProc.OnLogStatus += GetLogStatusDelegate();
            DoctrinaProc.OnProgressStatus += new Migracion.Process.ProgressStatus(ProgressStatus);

            DoctrinaProc.ProcesarDoctrina = true;

            this.btnDetenerJuris.Visible = true;
            this.btnProcesarJurisprudencia.Visible = false;
            this.btnProcesarDoctrina.Visible = false;
            this.btnObras.Visible = false;
            this.btnProcesarLegislacion.Visible = false;

            if (!Directory.Exists(this.txtOutputJuris.Text))
            {
                Directory.CreateDirectory(this.txtOutputJuris.Text);
            }

            DoctrinaProc.SQLText = this.txtSql.Text;
            DoctrinaProc.OutputPath = this.txtOutputJuris.Text;
            DoctrinaProc.AbeledoId = this.txtCitaAp.Text;            

            bkWorkerJuris.RunWorkerAsync();

        }

        private void btnObras_Click(object sender, EventArgs e)
        {
            LegislacionProc = null;
            DoctrinaProc = new DoctrinaProc();
            JurisprudenciaProc = null;

            DoctrinaProc.OnLogStatus += GetLogStatusDelegate();
            DoctrinaProc.OnProgressStatus += new Migracion.Process.ProgressStatus(ProgressStatus);

            DoctrinaProc.ProcesarDoctrina = false;

            DoctrinaProc.ProcesarSoloIndice = this.chkSoloIndice.Checked;
            DoctrinaProc.ProcesarSoloIdCuerpo = this.chkSoloIdCuerpo.Checked;
            if(!String.IsNullOrEmpty(this.txtIdCuerpoObra.Text))
            {
                DoctrinaProc.IdCuerpoParam = Convert.ToInt32(this.txtIdCuerpoObra.Text);
            }

            this.btnDetenerJuris.Visible = true;
            this.btnProcesarJurisprudencia.Visible = false;
            this.btnProcesarDoctrina.Visible = false;
            this.btnObras.Visible = false;
            this.btnProcesarLegislacion.Visible = false;

            

            if (!Directory.Exists(this.txtOutputJuris.Text))
            {
                Directory.CreateDirectory(this.txtOutputJuris.Text);
            }

            DoctrinaProc.SQLText = this.txtSql.Text;
            DoctrinaProc.OutputPath = this.txtOutputJuris.Text;
            DoctrinaProc.AbeledoId = this.txtCitaAp.Text;

            bkWorkerJuris.RunWorkerAsync();

        }

        private void btnProcesarLegislacion_Click(object sender, EventArgs e)
        {
            LegislacionProc = new LegislacionProc();
            DoctrinaProc = null;
            JurisprudenciaProc = null;         

            LegislacionProc.OnLogStatus += GetLogStatusDelegate();
            LegislacionProc.OnProgressStatus += new Migracion.Process.ProgressStatus(ProgressStatus);      

            this.btnDetenerJuris.Visible = true;
            this.btnProcesarJurisprudencia.Visible = false;
            this.btnProcesarDoctrina.Visible = false;
            this.btnObras.Visible = false;
            this.btnProcesarLegislacion.Visible = false;

            if (!Directory.Exists(this.txtOutputJuris.Text))
            {
                Directory.CreateDirectory(this.txtOutputJuris.Text);
            }

            LegislacionProc.SQLText = this.txtSql.Text;
            LegislacionProc.OutputPath = this.txtOutputJuris.Text;
            LegislacionProc.AbeledoId = this.txtCitaAp.Text;            

            bkWorkerJuris.RunWorkerAsync();
        }

        void Proc_OnLogStatus(string id, string message, MigracionLogStatus logType)
        {
            ErrorLog errorLog = new ErrorLog();
            errorLog.Id = id;
            errorLog.Message = message;
            errorLog.Status = logType;
            bkWorkerJuris.ReportProgress(0, errorLog);
        }

        private void btnDetenerJuris_Click(object sender, EventArgs e)
        {
            if (JurisprudenciaProc != null)
            {
                JurisprudenciaProc.CancelarProceso = true;
            }
            else if (DoctrinaProc != null)
            {
                DoctrinaProc.CancelarProceso = true;
            }
            else if (LegislacionProc != null)
            {
                LegislacionProc.CancelarProceso = true;
            }
        }

        private void btnFolderJurisprudencia_Click(object sender, EventArgs e)
        {
            if (this.folderBrowserDialogJuris.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.txtOutputJuris.Text = this.folderBrowserDialogJuris.SelectedPath;
            }
        }

        private void btnOpenJurisFolder_Click(object sender, EventArgs e)
        {
            Process.Start(this.txtOutputJuris.Text);
        }

        private void MigracionAPSAE_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (LogFile != null)
            {
                LogFile.Close();
                LogFile = null;
            }
        }

        private void btnBorrarLog_Click(object sender, EventArgs e)
        {
            this.lstLog.Items.Clear();
        }

        private void btnGuardarTexto_Click(object sender, EventArgs e)
        {            
            string filePath = string.Empty;

            if (this.saveFileDialogGuardarText.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filePath = this.saveFileDialogGuardarText.FileName;
            }

            AddRemoveFile addRemovefile = new AddRemoveFile();
            addRemovefile.ExtaerArchivo(filePath, this.txtSql.Text);

            lstLog.Items.Add("Archivo Generado: " + filePath);
        }

        private void btnIncorporarArchivo_Click(object sender, EventArgs e)
        {
            string filePath = string.Empty;

            if (this.openFileDialogIncorporarText.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filePath = this.openFileDialogIncorporarText.FileName;
            }

            AddRemoveFile addRemovefile = new AddRemoveFile();
            addRemovefile.IncorporarArchivo(filePath, this.txtSql.Text);
            lstLog.Items.Add("Archivo Incorporado: " + filePath);
        }       
    }
}
